from django.http import Http404, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404, render_to_response
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login
#from django.contrib.auth.views import login
from issuesdev.issues.models import ProjectUser, Project, Question, Reply

# Helper functions
def projects_for_user(request):
	pulist = ProjectUser.objects.filter(user__username__exact=request.user.username)
	# TODO: There has to be a better way to do this:
	plist = [Project.objects.get(id=pu.project.id) for pu in pulist]
	return plist

def valid_project(request, project_id):
	#return ProjectUser.objects.filter(user__username__exact=request.user.username).filter(project__exact=project_id).count()
	pl = ProjectUser.objects.filter(user__username__exact=request.user.username).filter(project__exact=project_id)
	if pl.count() < 1:
		return None
	else:
		return pl[0].project


# Views

@login_required
def project_list(request):
	plist = projects_for_user(request)
	return render_to_response('issues/project_list.html', {'project_list': plist})

@login_required
def question_list(request, project_id):
	p = valid_project(request, project_id)
	if not p:
		return render_to_response('issues/invalid_project.html')
	latest_question_list = Question.objects.filter(project=project_id).order_by('-entry_date')
	return render_to_response('issues/question_list.html', {
		'latest_question_list': latest_question_list,
		#'project_id': project_id, 
		'project': p, 
	})

@login_required
def new_question(request, project_id):
	"""Handles entry of a new question."""
	p = valid_project(request, project_id)
	if not p:
		return render_to_response('issues/invalid_project.html')
	q = Question()
	q.question = request.POST['question']
	q.submitter = request.user
	q.project = p
	if False: #q.question == '':
		return render_to_response('issues/question_list.html', {
			'question': q.question, 
			'project_id': project_id, 
			'error_message': 'Please enter a question.'
		})
	else:
		q.save()
		return HttpResponseRedirect(reverse('issuesdev.issues.views.question_list', args=(project_id,)))

@login_required
def question_detail(request, project_id, question_id):
	p = valid_project(request, project_id)
	if not p:
		return render_to_response('issues/invalid_project.html')

	can_close = False
	try:
		q = Question.objects.get(pk=question_id)
		if q.project.id != p.id:
			raise Http404
		if q.answered != 'Y' and request.user.id == q.submitter.id:
			can_close = True
		rlist = q.reply_set.all().order_by('entry_date')
	except Question.DoesNotExist:
		raise Http404
	return render_to_response('issues/question_detail.html', {
		'request': request,
		'project': p, 
		'question': q, 
		'reply_list': rlist,
		'can_close': can_close,
	})

@login_required
def new_reply(request, project_id, question_id):
	""" Handles entry of a new reply."""
	p = valid_project(request, project_id)
	if not p:
		return render_to_response('issues/invalid_project.html')

	q = get_object_or_404(Question, pk=question_id)
	if q.project.id != p.id:
		raise Http404
	if q.answered == 'Y':
		raise Http404
	reply = Reply()
	reply.reply = request.POST['text']
	reply.question = q
	reply.submitter = request.user
	reply.save()
	q.num_replies += 1
	q.save()
	return HttpResponseRedirect(reverse('issuesdev.issues.views.question_detail', args=(p.id, q.id)))

@login_required
def close_question(request, project_id, question_id):
	"""Marks a question as closed."""
	p = valid_project(request, project_id)
	if not p:
		return render_to_response('issues/invalid_project.html')

	q = get_object_or_404(Question, pk=question_id)
	if q.project.id != p.id:
		raise Http404
	if request.user.id != q.submitter.id:
		raise Http404
	q.answered = 'Y'
	q.save()
	return HttpResponseRedirect(reverse('issuesdev.issues.views.question_detail', args=(p.id, q.id)))

def sitelogin(request):
	#if not request.post.has_key('username'):
	if request.method != 'POST':
		return render_to_response('issues/login.html')
	username = request.POST['username']
	password = request.POST['password']
	user = authenticate(username=username, password=password)
	if user is not None:
		if user.is_active:
			login(request, user)
			# Redirect to a success page.
			return HttpResponseRedirect(reverse('issuesdev.issues.views.project_list'))
		else:
			# Return a 'disabled account' error message
			return HttpResponseRedirect(reverse('issuesdev.issues.views.sitelogin'))
	else:
		# Return an 'invalid login' error message.
		return HttpResponseRedirect(reverse('issuesdev.issues.views.sitelogin'))


#OLD

def all_questions(request, question='', error_message=''):
	latest_question_list = Question.objects.all().order_by('-entry_date')[:20]
	return render_to_response('issues/all_questions.html', {
		'latest_question_list': latest_question_list,
		'question': question,
		'error_message': error_message
	})

@login_required
def my_account(request):
	return render_to_response('issues/my_account.html', {
		'request': request,
	})

def approve_reply(request, reply_id, approval_type):
	"""Handles approval of a reply (partial or complete)."""
	pass

